#include "FWKeyboard.h"
#include "FWGame.h"

FWKeyboard::FWKeyboard(FWGame* game)
{
	this->gameObject = game;
	this->di8 = 0;
	this->did8 = 0;
	ZeroMemory(&key,sizeof(key));

	HRESULT hr = DirectInput8Create(
		gameObject->hInstance, // hInstance cua chuong trinh
		DIRECTINPUT_VERSION, // tham so mac dinh
		IID_IDirectInput8, // co the tu define
		(void**)&this->di8, // con tro nhan gia tri tra ve
		NULL);
	if (FAILED(hr))
	{
		throw ERROR_CREATE_DEVICE;
	}

	hr = this->di8->CreateDevice(GUID_SysKeyboard,&this->did8,NULL);
	if (FAILED(hr))
	{
		throw ERROR_CREATE_KEYBOOARD;
	}
	
	hr = this->did8->SetDataFormat(&c_dfDIKeyboard);
	if (FAILED(hr))
	{
		throw ERROR_SETFORMAT;
	}
	
	hr = this->did8->SetCooperativeLevel(this->gameObject->hWnd,DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	if (FAILED(hr))
	{
		throw ERROR_SETCOOPERATIVE;
	}

	this->did8->Acquire();
}

FWKeyboard::~FWKeyboard(void)
{
}

void FWKeyboard::getState()
{
	HRESULT hr = this->did8->GetDeviceState(sizeof(this->key),(void**)(this->key));
	if (FAILED(hr))
	{
		this->did8->Acquire(); //lay quyen su dung keyboard;
	}
}

bool FWKeyboard::isKeyDown(int key)
{
	return this->key[key] & 0x80; 
}

void FWKeyboard::saveState()
{
}
